<template>
    <div>
        <el-card class="box-card" shadow="hover">
            <!-- 商品搜索表单-->
            <el-form  :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item v-if="tabName === '商品列表'" label="商品名称">
                    <el-input
                    v-model="queryParams.name"
                    placeholder="请输入商品名称"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                 <el-form-item  v-if="tabName === '商品列表'" label="商品价格">
                    <el-input-number
                    v-model="queryParams.minPrice" 
                    style="width:150px;" 
                    controls-position="right"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    size="small" />
                    <span>~</span>
                    <el-input-number
                    v-model="queryParams.maxPrice" 
                    style="width:150px;" 
                    controls-position="right"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    size="small" />
                </el-form-item>

                <el-form-item v-if="tabName === '售后列表'" label="关键字">
                    <el-input
                    v-model="queryParams.like"
                    placeholder="订单编号,联系人电话"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item v-if="tabName === '商品列表'" label="状态">
                    <el-select
                    v-model="queryParams.isPutaway"
                    placeholder="状态"
                    clearable
                    size="small"
                    style="width: 240px">
                        <el-option
                        v-for="statu in statusOptions"
                        :key="statu.value"
                        :label="statu.label"
                        :value="statu.value"
                        />
                    </el-select>
                </el-form-item> 
                <el-form-item v-if="tabName === '售后列表'" label="状态">
                    <el-select
                    v-model="queryParams.isAgree"
                    placeholder="状态"
                    clearable
                    size="small"
                    style="width: 240px">
                        <el-option
                        v-for="statu in statusOptions"
                        :key="statu.value"
                        :label="statu.label"
                        :value="statu.value"
                        />
                    </el-select>
                </el-form-item> 
                <el-form-item label="时间段">
                    <el-date-picker
                    v-model="date"
                    size="small"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    <el-button 
                    v-if="tabName === '商品列表'" 
                    icon="el-icon-plus" 
                    size="mini" 
                    @click="addCommodity()" 
                    type="primary">
                    添加商品
                    </el-button>
                </el-form-item>
            </el-form>

            <el-table
            v-if="tabName === '商品列表'"
            :data="tableData"
            stripe
            style="width: 100%">
                <el-table-column
                prop="id"
                label="id"
                align="center">
                </el-table-column>
                <el-table-column
                prop="litimgUrl"
                label="商品缩略图"
                align="center">
                    <template slot-scope="scope">
                        <img v-if="scope.row.litimgUrl" :src="scope.row.litimgUrl" class="url">
                    </template>
                </el-table-column>
                <el-table-column
                prop="name"
                label="商品名称"
                align="center">
                </el-table-column>
                <el-table-column
                prop="intro"
                label="商品简介"
                align="center">
                </el-table-column>
                <el-table-column
                prop="price"
                label="商品价格"
                align="center">
                    <template slot-scope="scope">
                        <el-popover  trigger="hover" placement="top">
                            <div  v-for="item in scope.row.modelList" :key="item.id">
                                <span>规格: {{ item.name }}</span>
                                <span>价格: {{ item.price }}</span>
                            </div>
                            
                            <div slot="reference" class="name-wrapper">
                                <el-tag v-if="scope.row.model == true" size="medium">多规格</el-tag>
                            </div>
                        </el-popover>
                        
                        <span v-if="scope.row.model == false" >{{scope.row.price}}</span>
                        <!-- <span v-if="scope.row.model == true">多规格</span>
                        <span v-else>{{scope.row.price}}</span> -->
                    </template>
                </el-table-column>
                <el-table-column
                prop="count"
                label="商品数量"
                align="center">
                </el-table-column>
                <el-table-column
                prop="facilityTypeValue"
                label="商品类型"
                align="center">
                </el-table-column>
                <el-table-column
                prop="purchasingTypesValue"
                label="设备租赁"
                align="center">
                </el-table-column>
                <el-table-column
                prop="putaway"
                label="商品状态"
                align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.putaway === true">上架</span>
                        <span v-else>下架</span>
                    </template>
                </el-table-column>
                <el-table-column
                prop="putawayDate"
                label="添加日期"
                width="100px"
                align="center">
                </el-table-column>
                <el-table-column
                prop="cashPledge"
                label="商品押金"
                align="center">
                </el-table-column>
                <el-table-column
                prop="facilityDetailsTypeValue"
                label="所属分类"
                align="center">
                </el-table-column>
                <el-table-column
                width="100"
                fixed="right"
                label="操作"
                align="center">
                    <template slot-scope="scope">
                        <i class="el-icon-edit" style="font-size: 12px;color: #409EFF;cursor:pointer;" @click="updateCommodity(scope.row.id)">编辑</i>
                        <i class="el-icon-delete" style="font-size: 12px;color: #F56C6C;cursor:pointer;"  @click="removeCommodity(scope.row.id)">删除</i>
                    </template>
                </el-table-column>
            </el-table>

            <el-table
            v-if="tabName === '售后列表'"
            :data="tableData"
            stripe
            style="width: 100%">
                <el-table-column
                prop="id"
                label="id"
                align="center">
                </el-table-column>
                <el-table-column
                prop="orderId"
                label="订单编号"
                align="center">
                </el-table-column>
                <el-table-column
                prop="typeValue"
                label="售后方式"
                align="center">
                </el-table-column>
                <el-table-column
                prop="phone"
                label="联系人电话"
                align="center">
                </el-table-column>
                <el-table-column
                prop="explain"
                label="售后说明"
                align="center">
                </el-table-column>
                <el-table-column
                prop="explainImgUrl"
                label="售后凭证"
                align="center">
                </el-table-column>
                <el-table-column
                prop="createDate"
                label="售后申请日期"
                width="100px"
                align="center">
                </el-table-column>
                <el-table-column
                prop="isAgree"
                label="处理状态"
                align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.isAgree==null">未处理</span>
                        <span v-else-if="scope.row.isAgree==true  || scope.row.isAgree==false">已处理</span>
                    </template>
                </el-table-column>
                <el-table-column
                prop="note"
                label="备注"
                align="center">
                </el-table-column>
                <el-table-column
                width="100"
                fixed="right"
                label="操作"
                align="center">
                    <template slot-scope="scope">
                        <i class="el-icon-edit" style="font-size: 12px;color: #409EFF;cursor:pointer;" @click="updateAfterSale(scope.row.id)">编辑</i>
                        <i class="el-icon-delete" style="font-size: 12px;color: #F56C6C;cursor:pointer;"  @click="removeAfterSale(scope.row.id)">删除</i>
                    </template>
                </el-table-column>
            </el-table>
            
            <!--分页栏-->
            <el-pagination
            background
            align="center"
            @size-change="handleSizeChange($event,111)"
            @current-change="data()"
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </el-card>
        <!--添加框/编辑框-->
        <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        :width="dialogWidth"
        :before-close="handleClose">
            <el-form 
            label-width="80px" 
            :model="form" 
            ref="form"
            v-if="tabName === '商品列表'">
                <el-row type="flex" class="row-bg">
                    <el-col span="10">
                        <el-form-item label="轮播图">
                            <el-upload
                                class="upload-demo"
                                multiple
                                ref="upload"
                                list-type="picture"
                                :auto-upload="false"
                                :action="uploadUrl"
                                :headers="headers"
                                :file-list="fileList"
                                :on-success="handleCarouselSuccess"
                                :on-remove="handleRemove"
                                :before-upload="beforeUpload"> 
                                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload()">上传到服务器</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" class="row-bg">
                    <el-col>
                        <el-form-item label="缩略图">
                            <el-upload
                                class="avatar-uploader"
                                :action="uploadUrl"
                                :headers="headers"
                                :show-file-list="false"
                                :on-success="handlelitimgSuccess"
                                :before-upload="beforeLitimgUpload">
                                    <img v-if="img" :src="form.litimgUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span=10>
                        <el-form-item label="商品名称">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col span=10>
                        <el-form-item label="商品简介">
                            <el-input v-model="form.intro"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col span=10>
                        <el-form-item label="商品类型">
                            <div class="block">
                                <el-select
                                v-model="form.facilityType"
                                style="width:100%"
                                 @change="facilityTypeChange">
                                    <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col span=10>
                        <el-form-item 
                        label="所属分类">
                            <el-select 
                            :disabled="form.facilityType == null"
                            v-model="form.facilityDetailsType" 
                            style="width:100%">
                                <el-option
                                    v-for="item in detailsTypeOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="form.facilityType == 0" span=1>
                        <el-button style="padding-left:20px" type="text" @click="addSpec()">添加规格</el-button>
                    </el-col>
                </el-row>
                <el-row
                v-for="(spec, index) in form.modelList"
                :key="spec.key"
                :prop="'specs.' + index + '.specName'">
                    <el-col span="10">
                        <el-form-item 
                        :label="'规格' + (index+1) + '名称'">
                            <el-input  v-model="spec.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col span="10">
                        <el-form-item 
                        :label="'规格' + (index+1) + '价格'">
                            <el-input-number
                            style="width:100%;"
                            controls-position="right"
                            :min="0"
                            :precision="2"
                            :step="0.1"
                            v-model="spec.price">
                            </el-input-number>   
                        </el-form-item>
                    </el-col>
                    <el-button style="padding-left:20px" type="text" @click.prevent="removeSpec(spec)">删除</el-button>
                </el-row>
                <el-row >
                     <el-col span="10">
                        <el-form-item label="商品状态">
                            <el-select
                            style="width:100%"
                            v-model="form.putaway"
                            placeholder="状态"
                            clearable>
                                <el-option
                                v-for="statu in statusOptions"
                                :key="statu.value"
                                :label="statu.label"
                                :value="statu.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> 
                   
                    <el-col span="10">
                        <el-form-item 
                        label="商品数量">
                            <el-input  v-model="form.count"></el-input>
                        </el-form-item>
                    </el-col>  
                </el-row>
                <el-row>
                    <el-col span=10>
                        <el-form-item
                        v-if="form.facilityType == 0"
                        label="购买类型">
                            <el-select
                                v-model="form.purchasingTypes"
                                style="width:100%">
                                    <el-option
                                    v-for="item in purchasingTypes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    </el-option>
                                </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col span=10>
                        <el-form-item 
                        label="商品价格">
                            <el-input-number
                            style="width:100%;"
                            controls-position="right"
                            :min="0"
                            :precision="2"
                            :step="0.1"
                            v-model="form.price">
                            </el-input-number>
                        </el-form-item>
                    </el-col>  
                </el-row>
                <el-row>
                    <el-col 
                    v-if="form.purchasingTypes == 1 || form.purchasingTypes == 2" 
                    span=10>
                        <el-form-item label="商品押金">
                            <el-input-number
                            style="width:100%;"
                            controls-position="right"
                            :min="0"
                            :precision="2"
                            :step="0.1"
                            v-model="form.cashPledge">
                            </el-input-number>
                        </el-form-item>
                    </el-col> 
                </el-row>
                <el-form-item label="html详情">
                    <div style="height: 18em;">
                        <Editor placeholder="请输入内容" v-model="form.details"/>
                    </div>
                </el-form-item>
            </el-form>
            <el-form 
            ref="form" 
            :model="form" 
            v-if="tabName === '售后列表'"
            label-width="80px">
                <el-form-item label="状态:">
                     <el-radio-group v-model="form.isAgree">
                        <el-radio :label=true>同意</el-radio>
                        <el-radio  :label=false>不同意</el-radio>
                     </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input  v-model="form.note"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submmit()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import Editor from '@/components/Editor'
import { list,add,del,update,commodity,inquire,detailed } from '@/api/app_pages/commodity'
import { afterSaleList,afterSaleAdd,afterSaleDel,afterSaleUpdate,afterSale,afterSaleInquire } from '@/api/app_pages/afterSale'
import { getToken } from '@/utils/auth'
import { getDicts } from '@/api/system/dict/data'
export default {
    components:{
        Editor
    },
    data(){
        return {
            queryParams:{},
            options:[],
            tableData: [],
            size: 20,
            currentPage: 1,
            total: 0,
            dialogVisible: false,
            dialogTitle:'',
            form:{
                modelList: []
            },
            commodityImageUrl:'',
            tabName: '商品列表',
            statusOptions:[],
            keyword: '',
            uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
            headers: {
                Authorization: 'Bearer ' + getToken()
            },
            fileList: [],
            img: false,
            detailsTypeOptions: [],
            date: [],
            purchasingTypes:[],
            dialogWidth: ''
        }
    },
    created(){
        this.tabName = this.$route.path.split("/")[2]
        this.queryParams = {}
        if(this.tabName == '售后列表'){
            this.dialogWidth = '20%'
            this.statusOptions = [{label: '已处理',value: true},{label: '未处理',value: false}]
            this.keyword = '订单编号、联系人电话'
        }else{
            this.dialogWidth = '50%'
            this.statusOptions = [{label: '上架',value: true},{label: '下架',value: false}]
            this.keyword = '办公耗材、设备采购、设备租赁'
        }
        this.options = [{
            value: '0',
            label: '设备'
        },
        {
            value: '1',
            label: '办公耗材',
        }]
        this.data()
        if(this.tabName != '售后列表'){
            detailed(0).then(res => {
                sessionStorage.setItem('device', JSON.stringify(res.rows));
            })
            detailed(1).then(res => {
                sessionStorage.setItem('consumables', JSON.stringify(res.rows));
            })
            getDicts('g_purchasing_types').then(res => {
                let data = []
                res.data.forEach(item => {
                    data.push({label:item.dictLabel,value:item.dictValue})
                });
                this.purchasingTypes = data
            })
        }
    },
    methods:{
        data(){
            if(this.tabName == '售后列表'){
                afterSaleList(this.size,this.currentPage).then(res => {
                    this.tableData = res.rows
                    this.total = parseInt(res.total)
                })
            }else{
                list(this.size,this.currentPage).then(res => {
                    this.tableData = res.rows
                    this.total = parseInt(res.total)
                })
            }
            
        },
        addSpec() {
            this.form.modelList.push({
                name: '',
                price: 0
            });
        },
        removeSpec(item) {
            let index = this.form.modelList.indexOf(item)
            if (index !== -1) {
                this.form.modelList.splice(index, 1)
            }
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        },
        updateAfterSale(id){
            this.dialogTitle = '编辑售后'
            this.dialogVisible = true
            this.form.id = parseInt(id);  
            afterSale(this.form.id).then(res => {
                this.form = res.data
            })
        },
        updateCommodity(id){
            this.dialogTitle = '编辑商品'
            this.dialogVisible = true
            this.form.id = parseInt(id);  
            this.fileList = [] 
            let imgData = []
            new Promise((resolve,reject) => {
                commodity(this.form.id).then(res => {
                    this.form = res.data
                    imgData = res.data.carouselUrl.split(';')
                    this.img = true
                    resolve()
                })
            }).then(res => {
                imgData.forEach(item => {
                    this.form.carouselUrl = ''
                    if(item != "" ){
                        this.form.carouselUrl += item+";"
                        this.fileList.push({name:item,url:item})
                    } 
                });
                this.facilityTypeChange()
            })    
        },  
        submmit(){
            if(this.tabName == '商品列表'){
                if(this.form.modelList.length < 1){
                    this.form.isModel = false
                }else{    
                    this.form.isModel = true
                }
                if (this.form.purchasingTypes == 0){
                    this.form.cashPledge = 0
                }
                this.form.isPutaway = this.form.putaway
                this.$delete(this.form,'purchasingTypesValue')
                this.$delete(this.form,'facilityTypeValue')
                this.$delete(this.form,'facilityDetailsTypeValue')
                this.$delete(this.form,'putawayDate')
                this.$delete(this.form,'model')
                this.$delete(this.form,'putaway')
                this.form.modelList.forEach(item =>{
                    this.$delete(item,'commodityId')
                })
            }
            
            
            if(this.dialogTitle == '编辑商品'){
                new Promise((resolve,reject) =>{
                    update(this.form).then(res => {
                        this.dialogVisible = false
                        resolve()
                    })
                }).then(res => {
                    this.data()
                })
            
            }else if(this.dialogTitle == '编辑售后'){
                new Promise((resolve,reject) =>{
                    afterSaleUpdate(this.form).then(res => {
                        this.dialogVisible = false
                        resolve()
                    })
                }).then(res => {
                    this.data()
                })

            }else{
                new Promise((resolve,reject) =>{
                    add(JSON.stringify(this.form)).then(res => {
                        this.dialogVisible = false
                        resolve()
                    })  
                }).then(res => {
                    this.data()
                })
            }
        } ,
        handleCarouselSuccess(res, file,fileList) {
            this.form.carouselUrl = '' 
            fileList.forEach(item => {
                console.info(res)
                this.form.carouselUrl += res.fileName+";"
            })
        },
        handleRemove(file, fileList) {
            this.form.carouselUrl = '' 
            fileList.forEach(item => {
                this.form.carouselUrl += item.url+";"
            })   
        },
        handlelitimgSuccess(res, file) {
            this.form.litimgUrl = res.fileName
            this.img = true
        },
        beforeUpload(file) {
            const isImg = file.type.indexOf("image/")==0;
            if (!isImg) {
                this.$message.error('图片格式不正确!');
            }
            return isImg;
        },
        beforeLitimgUpload(file){
            this.beforeUpload(file)
        },
        removeCommodity(id){
            del(id).then(res => {
                this.$message('删除成功')
                this.data()
            })
        },
        removeAfterSale(id){
            afterSaleDel(id).then(res => {
                this.$message('删除成功')
                this.data()
            })
        },
        handleQuery(){
            this.queryParams.startDate = this.date[0]
            this.queryParams.endDate = this.date[1]
            this.queryParams.pageSize = this.pageSize
            this.queryParams.pageNum = this.pageNum
            if(this.tabName == '售后列表'){
                afterSaleInquire(this.queryParams).then(res =>{
                    this.tableData = res.rows
                    this.total = parseInt(res.total)
                })
            }else{
                inquire(this.queryParams).then(res =>{
                    this.tableData = res.rows
                    this.total = parseInt(res.total)
                })
            }
        },
        resetQuery(){
            this.queryParams = {}
            this.date = []
        },
        addCommodity(){
            this.dialogTitle = '添加商品'
            this.form={
                modelList:[]
            }
            this.img = false
            this.fileList = []
            this.dialogVisible = true
        },
        submitUpload() {
            this.$refs.upload.submit();
        },
        facilityTypeChange(){
            if(this.form.facilityType == 0){
                this.detailsTypeOptions = JSON.parse(sessionStorage.getItem('device'))
            }else{
                this.detailsTypeOptions = JSON.parse(sessionStorage.getItem('consumables'))
            }
        },
        handleSizeChange(val,e) {
            this.size = val;
            this.data()
        },
    }
}
</script>
<style>
    .text {
    font-size: 14px;
    }
    .item {
    margin-bottom: 18px;
    }
    .clearfix:before,
    .clearfix:after {
    display: table;
    content: "";
    }
    .clearfix:after {
    clear: both
    }
    .box-card {
    margin: 0 auto;
    }
    
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .url {
    width: 50px;
    height: 50px;
    display: block;
    margin: 0 auto;
    }
</style>